package sg.edu.nus.iss.billing.gui;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
import javax.swing.border.TitledBorder;

import sg.edu.nus.iss.billing.controller.CustomerController;
import sg.edu.nus.iss.billing.entity.Customer;
import sg.edu.nus.iss.billing.entity.RecordState;
import sg.edu.nus.iss.billing.exception.ControllerException;
import sg.edu.nus.iss.billing.exception.ValidationException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.gui.component.ValidateJTextField;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;
import sg.edu.nus.iss.billing.validation.ValidationRule;


public class SearchCustomerComplaintsPanel extends JPanel {
  /**
	 * 
	 */
  private static final long serialVersionUID = -6086348172314561666L;
  // search field
  private ValidateJTextField searchTxt;
  // radio buttons to change meaning of search field
  private JRadioButton complaintIDrdbtn;
  private JRadioButton customerNRICrdbtn;
  // call back when user clicks on the search button
  private ActionListener listener;
  // complaint ID
  private String complaintID;
  // NRIC
  private String nric;

  /**
   * Get the complaint ID entered in this panel
   * 
   * @return the complaint ID entered in this panel
   */
  public String getComplaintID() {
    return this.complaintID;
  }

  /**
   * Get the NRIC entered in this panel
   * 
   * @return the NRIC entered in this panel
   */
  public String getNRIC() {
    return this.nric;
  }

  /*
   * Called when the customer ID radio button is selected
   */
  void customerNRICrdbtnSelected() {
    this.searchTxt.setFieldName(MessageKeyManager.getMessage("label.nric"));
    this.searchTxt.setRules(ValidationRule.NOT_NULL, ValidationRule.NRIC);
    Customer customer = SessionContext.getCustomer();
    if ((customer != null) && (customer.getActive() == RecordState.ACTIVE)) {
      this.searchTxt.setText(SessionContext.getCustomer().getNRIC());
    }
  }

  /*
   * Called when the complaint ID radio button is selected
   */
  void complaintIDrdbtnSelected() {
    this.searchTxt.setFieldName(MessageKeyManager
        .getMessage("label.complaintID"));
    this.searchTxt.setRules(ValidationRule.NOT_NULL);
    this.searchTxt.setText("");
  }

  /*
   * Called when the search button is pressed
   */
  void searchButtonPressed() {
    CustomerController customerController = new CustomerController();
    try {
      if (this.customerNRICrdbtn.isSelected()) {
        // search for the customer
        Customer customer = customerController.getCustomerByNRIC(this.searchTxt
            .getValidatedText());
        // save it into the context
        if (customer.getActive() == RecordState.ACTIVE) {
          SessionContext.setCustomer(customer);
          this.nric = customer.getNRIC();
        } else {
          this.nric = null;
          JOptionPane.showMessageDialog(null, "Customer has already been DELETED!", "Search Complaint", JOptionPane.INFORMATION_MESSAGE);
        }
        // save the NRIC, reset the complaint ID
        this.complaintID = null;
      } else {
        // save the complaint ID, reset the NRIC
        this.nric = null;
        this.complaintID = this.searchTxt.getValidatedText();
      }
      this.listener.actionPerformed(null);

      // catch blocks will show the error thrown to the user
    } catch (ControllerException ce) {
      this.searchTxt.setText("");
      ErrorDialog.showControllerErrorMessageDialog(ce);
    } catch (ValidationException ve) {
      this.searchTxt.setText("");
      ErrorDialog.showValidationErrorMessageDialog(ve);
    } catch (Exception ex) {
      this.searchTxt.setText("");
      ErrorDialog.showUnhandledErrorMessageDialog(ex);
    }
  }

  /**
   * Create the panel.
   * 
   * @param actionListener
   *          to be called when the user clicks on the search button
   */
  public SearchCustomerComplaintsPanel(ActionListener actionListener) {
    // save the action listener
    this.listener = actionListener;

    // set the layout for this panel
    setLayout(new BorderLayout());

    JPanel containingPanel = new JPanel(new BorderLayout());
    containingPanel.setBorder(new TitledBorder(null, MessageKeyManager
        .getMessage("border.search"), TitledBorder.LEADING, TitledBorder.TOP,
        null, null));
    add(containingPanel, BorderLayout.CENTER);
    
    // set the layout for the containing panel
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0, 80, 80, 0, 0 };
    gridBagLayout.rowHeights = new int[] { 0, 0 };
    gridBagLayout.columnWeights = new double[] { 0.0, 0.0, 0.0, 0.0,
        Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE };

    // actual components will be stored in the content panel
    JPanel contentPanel = new JPanel(gridBagLayout);
    containingPanel.add(contentPanel, BorderLayout.NORTH);

    // initialize the search field, assume the customer NRIC radio button is
    // selected at start up
    this.searchTxt = new ValidateJTextField(
        MessageKeyManager.getMessage("label.nric"));
    customerNRICrdbtnSelected();

    // initialize the search button and corresponding action
    JButton searchButton = new JButton(
        MessageKeyManager.getMessage("button.lookup"));
    searchButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        searchButtonPressed();
      }
    });

    // initialize the labels and add it to the content panel
    GridBagHelper.addLabel(contentPanel,
        MessageKeyManager.getMessage("label.selectOption"),
        SwingConstants.RIGHT, 0, 0, GridBagConstraints.WEST, 0,
        GridBagHelper.INSETS_SMALL);
    
    // initialize the radio buttons and add it to the content panel
    this.customerNRICrdbtn = GridBagHelper.addRadioButton(contentPanel,
        MessageKeyManager.getMessage("label.nric"), 1, 0, 0,
        GridBagHelper.INSETS_SMALL);
    this.customerNRICrdbtn.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        customerNRICrdbtnSelected();
      }
    });
    this.complaintIDrdbtn = GridBagHelper.addRadioButton(contentPanel,
        MessageKeyManager.getMessage("label.complaintID"), 2, 0, 0,
        GridBagHelper.INSETS_SMALL);
    this.complaintIDrdbtn.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        complaintIDrdbtnSelected();
      }
    });
    this.customerNRICrdbtn.setSelected(true);

    // group the radio buttons together
    ButtonGroup group = new ButtonGroup();
    group.add(this.complaintIDrdbtn);
    group.add(this.customerNRICrdbtn);

    // add the remaining components to the content panel
    GridBagHelper.addComponent(contentPanel, this.searchTxt, 1, 1, 2,
        GridBagHelper.INSETS_SMALL);
    GridBagHelper.addComponent(contentPanel, searchButton, 3, 1, 0,
        GridBagHelper.INSETS_SMALL);
    
    // check the current context, if NRIC has been set, populate the search field
    Customer sessionContextCustomer = SessionContext.getCustomer();
    if (sessionContextCustomer != null) {
      this.searchTxt.setText(sessionContextCustomer.getNRIC());
    }
  }
}